<template>
  <div class="order-container">
    <h1>订单</h1>
    
    <div class="order-actions">
      <el-button type="primary" icon="Plus" @click="showCreateDialog">新建陪护订单</el-button>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索订单"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    
    <el-table :data="filteredOrderList" style="width: 100%" v-loading="loading">
      <el-table-column prop="orderId" label="订单编号" width="120" />
      <el-table-column prop="name" label="护工姓名" width="120" />
      <el-table-column prop="createTime" label="申请时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="conditionDescription" label="陪护需求详情" min-width="200">
        <template #default="scope">
          {{ scope.row.conditionDescription || '无详情' }}
        </template>
      </el-table-column>
      <el-table-column prop="paymentStatus" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.paymentStatus)">
            {{ getStatusText(scope.row.paymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" plain @click="handleViewDetail(scope.row)">查看详情</el-button>
          <el-button 
            v-if="scope.row.paymentStatus === '1'" 
            type="danger" 
            size="small" 
            plain
            @click="handleCancelOrder(scope.row)"
          >取消订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.orderId }}</el-descriptions-item>
        <el-descriptions-item label="护工姓名">{{ currentOrder.name || '暂无分配' }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ formatDateTime(currentOrder.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ formatDateTime(currentOrder.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ formatDateTime(currentOrder.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="陪护需求详情">{{ currentOrder.conditionDescription || '无详情' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentOrder.paymentStatus)">
            {{ getStatusText(currentOrder.paymentStatus) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 创建订单弹窗 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建陪护订单"
      width="500px"
    >
      <el-form :model="orderForm" :rules="orderRules" ref="orderFormRef" label-width="100px">
        <el-form-item label="护工" prop="caregiverId">
          <el-select
            v-model="orderForm.caregiverId"
            placeholder="请选择护工"
            style="width: 100%"
            @change="handleCaregiverChange"
          >
            <el-option
              v-for="caregiver in caregiverList"
              :key="caregiver.caregiverId"
              :label="caregiver.name"
              :value="caregiver.caregiverId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="orderForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="orderForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrder">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCarerequest } from '@/api/carerequest'
import { listServerorder, updateServerorder, addServerorder } from '@/api/serverorder'
import { getCaregiver, listCaregiver } from '@/api/caregiver'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const loading = ref(false)
const searchKeyword = ref('')
const orderList = ref([])
const detailDialogVisible = ref(false)
const createDialogVisible = ref(false)
const currentOrder = ref({})
const caregiverList = ref([]) // 护工列表

// 过滤后的订单列表
const filteredOrderList = computed(() => {
  let result = orderList.value

  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      (item.orderId && item.orderId.toString().includes(keyword)) ||
      (item.name && item.name.toLowerCase().includes(keyword))
    )
  }

  return result
})

// 创建订单表单
const orderFormRef = ref(null)
const orderForm = reactive({
  userId: '',
  caregiverId: '', // 护工ID
  startTime: '',
  endTime: '',
  paymentStatus: '1' // 默认待接单状态
})

// 表单验证规则
const orderRules = {
  caregiverId: [{ required: true, message: '请选择护工', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && orderForm.startTime && value <= orderForm.startTime) {
          callback(new Error('结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 获取订单列表
const getOrderList = async () => {
  if (!userStore.isLoggedIn) {
    userStore.loadUserInfo()
  }
  
  loading.value = true
  try {
    // 使用当前登录用户ID查询该用户的订单
    const query = { userId: userStore.userId }
    const res = await listServerorder(query)
    orderList.value = res || []
    console.log(orderList.value)
    
    // 获取护工信息和陪护需求详情
    await fetchCaregiverNames()
    await fetchCareRequestDetails()
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取护工姓名
const fetchCaregiverNames = async () => {
  for (const order of orderList.value) {
    if (order.caregiverId) {
      try {
        const caregiverInfo = await getCaregiver(order.caregiverId)
        console.log(caregiverInfo)
        if (caregiverInfo) {
          order.name = caregiverInfo.name
        }
      } catch (error) {
        console.error(`获取护工信息失败，ID: ${order.caregiverId}`, error)
      }
    }
  }
}

// 获取陪护需求详情
const fetchCareRequestDetails = async () => {
  for (const order of orderList.value) {
    if (order.requestId) {
      try {
        const requestInfo = await getCarerequest(order.requestId)
        if (requestInfo && requestInfo.conditionDescription) {
          order.conditionDescription = requestInfo.conditionDescription
        }
      } catch (error) {
        console.error(`获取陪护需求详情失败，ID: ${order.requestId}`, error)
      }
    }
  }
}

// 查看订单详情
const handleViewDetail = (row) => {
  currentOrder.value = row
  
  // 如果有护工ID但没有名字，尝试获取护工信息
  if (row.caregiverId && !row.name) {
    fetchCaregiverName(row.caregiverId).then(name => {
      if (name) {
        currentOrder.value.name = name
      }
    })
  }
  
  // 如果有请求ID但没有陪护需求详情，尝试获取
  if (row.requestId && !row.conditionDescription) {
    fetchCareRequestDetail(row.requestId).then(description => {
      if (description) {
        currentOrder.value.conditionDescription = description
      }
    })
  }
  
  detailDialogVisible.value = true
}

// 获取单个护工的姓名
const fetchCaregiverName = async (caregiverId) => {
  try {
    const caregiverInfo = await getCaregiver(caregiverId)
    return caregiverInfo?.name
  } catch (error) {
    console.error(`获取护工信息失败，ID: ${caregiverId}`, error)
    return null
  }
}

// 获取单个陪护需求详情
const fetchCareRequestDetail = async (requestId) => {
  try {
    const requestInfo = await getCarerequest(requestId)
    return requestInfo?.conditionDescription
  } catch (error) {
    console.error(`获取陪护需求详情失败，ID: ${requestId}`, error)
    return null
  }
}

// 取消订单
const handleCancelOrder = (row) => {
  ElMessageBox.confirm('确认取消该订单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await updateServerorder({
        orderId: row.orderId,
        paymentStatus: '4' // 已取消
      })
      ElMessage.success('订单已取消')
      getOrderList() // 刷新列表
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败，请重试')
    }
  }).catch(() => {})
}

// 获取护工列表
const getCaregiverList = async () => {
  try {
    const res = await listCaregiver({})
    caregiverList.value = res || []
  } catch (error) {
    console.error('获取护工列表失败:', error)
    ElMessage.error('获取护工列表失败，请重试')
  }
}

// 显示创建订单对话框
const showCreateDialog = async () => {
  orderForm.userId = userStore.userId
  orderForm.caregiverId = ''
  orderForm.startTime = ''
  orderForm.endTime = ''
  
  // 获取护工列表
  await getCaregiverList()
  
  createDialogVisible.value = true
}

// 处理护工选择变化
const handleCaregiverChange = (caregiverId) => {
  // 可以在这里添加额外的逻辑，例如根据护工ID获取更多信息
  console.log('选择的护工ID:', caregiverId)
}

// 创建订单
const handleCreateOrder = () => {
  orderFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      // 构建订单数据
      const orderData = {
        userId: orderForm.userId,
        caregiverId: orderForm.caregiverId,
        startTime: orderForm.startTime instanceof Date ? orderForm.startTime.toISOString() : orderForm.startTime,
        endTime: orderForm.endTime instanceof Date ? orderForm.endTime.toISOString() : orderForm.endTime,
        paymentStatus: orderForm.paymentStatus
      }
      
      console.log('提交的订单数据:', orderData)
      await addServerorder(orderData)
      ElMessage.success('订单创建成功')
      createDialogVisible.value = false
      getOrderList() // 刷新列表
    } catch (error) {
      console.error('创建订单失败:', error)
      ElMessage.error('创建订单失败，请重试')
    }
  })
}

// 处理搜索
const handleSearch = () => {
  // 执行搜索操作
}

const getStatusText = (status) => {
  const statusMap = {
    '1': '待接单',
    '2': '进行中',
    '3': '已完成',
    '4': '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    '1': 'warning',  // 待接单 - 黄色
    '2': 'primary',  // 进行中 - 蓝色
    '3': 'success',  // 已完成 - 绿色
    '4': 'info'      // 已取消 - 灰色
  }
  return typeMap[status] || 'info'
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.order-container {
  padding: 20px;
}

h1 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #303133;
}

.order-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

:deep(.el-button) {
  margin-left: 8px;
}

:deep(.el-button:first-child) {
  margin-left: 0;
}
</style> 